package com.mayikt.weixin.mp.handler;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.mayikt.base.BaseResponse;
import com.mayikt.constants.Constants;
import com.mayikt.core.util.RedisUtils;
import com.mayikt.member.output.dto.UserOutDTO;
import com.mayikt.weixin.feign.MemberServiceFeign;
import com.mayikt.weixin.mp.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {
    @Autowired
    private MemberServiceFeign memberServiceFeign;
    @Value("${mayikt.weixin.registration.code.message}")
    private String registrationMessage;
    @Value("${mayikt.weixin.default.registration.code.message}")
    private String defaultMessage;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                && weixinService.getKefuService().kfOnlineList()
                .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        String content = wxMessage.getContent();
        if (Validator.isMobile(content)){
            BaseResponse<UserOutDTO> resultUserInfo = memberServiceFeign.existMobile(content);
            //返回200说明找到该用户
            if (resultUserInfo.getCode().equals(Constants.HTTP_RES_CODE_200)){
                content = "该手机号"+content+"已注册！";
            }
            //返回203说明没有注册，取反说明没有返回203
            else if(!resultUserInfo.getCode().equals(Constants.HTTP_RES_CODE_EXISTMOBILE_203)){
                content = resultUserInfo.getMsg();
            } else {
                //一下是返回203执行的代码
//            如果是手机号
                String phoneNumber = content;
                String randomNumbers = RandomUtil.randomNumbers(6);
                content = registrationMessage.format(registrationMessage, randomNumbers);
                redisUtils.set(Constants.WEIXINCODE_KEY + phoneNumber, randomNumbers, Constants.WEIXINCODE_TIMEOUT);
            }
        } else {
            content = defaultMessage;
        }
        //TODO 组装回复消息
//        String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);

        return new TextBuilder().build(content, wxMessage, weixinService);
    }

}
